import { Component, ChangeDetectionStrategy, EventEmitter } from '@angular/core';
import { QuoteHeader } from "quote";
import { StripExtensionPipe, OptimizeUnitPipe } from "pipes";



@Component({
  // moduleId: module.id,
  selector: 'dynamic-table-content',
  templateUrl: 'dynamic-table-content.component.html',
  styleUrls: ['dynamic-table-content.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  inputs: [
    "data",
    "emptyRowData",
    "headers",
    "selectedSymbol",
    "currentSortBy",
    "currentSortType"
  ],
  outputs: [
    "headerClick",
    "valueClick",
    "valueDblClick"
  ]
})
export class DynamicTableContentComponent {
  stripPipe = new StripExtensionPipe();
  optimizeUnitPipe = new OptimizeUnitPipe();
  headerClick = new EventEmitter();
  valueClick = new EventEmitter();
  valueDblClick = new EventEmitter();

  hoverSymbol: string;

  getClass(value, header: QuoteHeader, isNotHead, vChangeRate, vPxChangeRate) {
    if (value === undefined || !header) return "";
    let classes = [];
    if (header.withUpOrDown && isNotHead) {
      // parseFloat(value) > 0 ? classes.push("go-up") : parseFloat(value) < 0 ? classes.push("go-down") : 0
      if (header.key === 'last_px') {
        parseFloat(vPxChangeRate) > 0 ? classes.push("go-up") : parseFloat(vPxChangeRate) < 0 ? classes.push("go-down") : 0;
      } else if (header.key === 'current') {
        parseFloat(vChangeRate) > 0 ? classes.push("go-up") : parseFloat(vChangeRate) < 0 ? classes.push("go-down") : 0;
      } else {
        parseFloat(value) > 0 ? classes.push("go-up") : parseFloat(value) < 0 ? classes.push("go-down") : 0
      }
    }
    if (header.class) {
      return [...header.class, classes].join(" ");
    }
    return classes;
  }

  getValue(value, header: QuoteHeader) {
    if (value === undefined || !header || value === "") return value;
    let v = header.transform ? header.transform.call(header, value) : value;
    if (header.key === "symbol") {
      return this.stripPipe.transform(value);
    }
    if (header.withUnit) {
      return this.optimizeUnitPipe.transform(v, 10000, 0, 2);
    }
    if (header.withPercent) {
      return parseFloat(v).toFixed(2) + "%";
    }
    if (!isNaN(parseFloat(value)) && header.key !== "$order") {
      return parseFloat(v).toFixed(2);
    }
    return v;
  }

  handleHeaderClick(header) {
    this.headerClick.next(header);
  }

  handleValueClick(value, stock, header) {
    this.valueClick.next({
      value,
      stock,
      header
    });
  }

  handleValueDblClick(value, stock, header) {
    this.valueDblClick.next({
      value,
      stock,
      header
    });
  }

  trackBySymbol(stock) {
    return stock.symbol;
  }
}
